<?php
/**
 * Created by : PhpStorm
 * author: sunqiangqiang
 * Date: 2020/4/21
 * Time: 2:52 下午
 */

namespace backend\controllers;


use backend\models\Materiel;
use backend\models\PurchaseOrder;
use backend\models\Supplier;
use backend\models\Warehouse;
use Yii;
use yii\web\AdminController;

class PurchaseOrderController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'purchaseOrder';


    public function actionIndex()
    {
        //仓库
        $warehouse_where = ['useFlg' => 1];
        $warehouse = Warehouse::find()->where($warehouse_where)->select('id,warehouseName')->asArray()->all();
        return $this->render('index', ['warehouse' => $warehouse]);
    }

    public function actionGetList()
    {
        $data = Yii::$app->request->post();
        $sql_list = 'SELECT jpo.*,wh.warehouseName,sup.supplierName FROM j_purchase_order jpo
                        LEFT JOIN j_warehouse wh ON jpo.warehouseId = wh.id
                        LEFT JOIN j_supplier sup ON jpo.supplierId = sup.id
                        WHERE 1=1 ';

        $sql_count = 'SELECT COUNT(0) CNT FROM j_purchase_order jpo WHERE 1=1 ';

        $sql = '';
        //订单状态
        if (isset($data['orderStatus']) && in_array($data['orderStatus'], array('0', '1', '2', '9'))) {
            $sql .= ' AND jpo.status=' . $data['orderStatus'];
        }
        //搜索关键字
        if (isset($data['orderNo']) && !empty($data['orderNo'])) {
            $sql .= ' AND jpo.orderNo like \'%' . $data['orderNo'] . '%\'';
        }
        //采购日期
        if (isset($data['purchaseDate']) && !empty($data['purchaseDate'])) {
            $dayArr = explode(' - ', $data['purchaseDate']);
            $sql .= ' AND jpo.purchaseDate >= "' . $dayArr[0] . '" AND jpo.purchaseDate <="' . $dayArr[1] . ' 23:59:59"';
        }
        //仓库
        if (isset($data['warehouseId']) && !empty($data['warehouseId'])) {
            $sql .= ' AND jpo.warehouseId=' . $data['warehouseId'];
        }

        if(isset($data['materielName']) && !empty($data['materielName'])){
            $sql .= " AND orderNo IN (SELECT orderNo FROM j_purchase_order_details WHERE materielName LIKE '%{$data['materielName']}%')";
        }




        $list_count = Yii::$app->db->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];

        $sql .= ' ORDER BY jpo.create_time DESC ';



        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db->createCommand($sql_list . $sql)->queryAll();
        if (empty($list)) {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        //操作日志
        return \yii\helpers\Json::encode($result);
    }


    public function actionEditOrderStatus()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['orderNo']) || !isset($data['status'])) {
            $this->retJson('参数错误', 500);
        }

        $sql = "SELECT * FROM j_purchase_order WHERE orderNo = '" . $data['orderNo'] . "'";
        $res = Yii::$app->db->createCommand($sql)->queryOne();
        if ($data['status'] == 2 && $res['status'] != 0) {
            $this->retJson('单据状态异常，请刷新后重试', 500);
        }
        if ($data['status'] == 9 && $res['status'] != 1) {
            $this->retJson('单据状态异常，请刷新后重试', 500);
        }

        $model = new PurchaseOrder();

        $order['status'] = $data['status'];

        if ($data['status'] == 2) {
            $order['cancelor'] = $model->getCreator();
            $order['cancel_time'] = date('Y-m-d H:i:s');
        }

        if ($data['status'] == 9) {
            $order['closeor'] = $model->getCreator();
            $order['close_time'] = date('Y-m-d H:i:s');
        }


        $transaction = Yii::$app->db->beginTransaction();
        try {
            $model::updateAll($order, "orderNo=:orderNo", array(':orderNo' => $data['orderNo']));
            $transaction->commit();
            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }

    public function actionAuditOrder()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['orderNo'])) {
            $this->retJson('参数错误', 500);
        }

        $sql = "SELECT * FROM j_purchase_order WHERE orderNo = '" . $data['orderNo'] . "'";
        $res = Yii::$app->db->createCommand($sql)->queryOne();
        if ($res['status'] != 0) {
            $this->retJson('单据状态异常，请刷新后重试', 500);
        }

        $model = new PurchaseOrder();

        $order['status'] = 1;
        $order['auditor'] = $model->getCreator();
        $order['audit_time'] = date('Y-m-d H:i:s');


        $transaction = Yii::$app->db->beginTransaction();
        try {
            $model::updateAll($order, "orderNo=:orderNo", array(':orderNo' => $data['orderNo']));
            $transaction->commit();
            $this->retJson('审核成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }


    public function actionDetail()
    {
        $data = Yii::$app->request->get();
        //仓库
        $warehouse_where = ['useFlg' => 1];
        $warehouse = Warehouse::find()->where($warehouse_where)->select('id,warehouseName,contacts,mobile,phone,province,city,area,address')->orderBy(['warehouseName'=>SORT_ASC,'province'=>SORT_ASC,'city'=>SORT_ASC,'area'=>SORT_ASC])->asArray()->all();

        $supplier = Supplier::find()->where(['useFlg' => 1])->select('id,supplierName')->asArray()->all();


        //订单信息
        $order = null;
        if (isset($data['orderNo']) && !empty($data['orderNo'])) {
            $sql = "SELECT * FROM j_purchase_order WHERE orderNo='" . $data['orderNo'] . "'";
            $order = Yii::$app->db->createCommand($sql)->queryOne();

            $sql = "SELECT * FROM j_purchase_order_details WHERE orderNo = '" . $data['orderNo'] . "'";
            $orderDtl = Yii::$app->db->createCommand($sql)->queryAll();
            $order['dtl'] = $orderDtl;

        }
        return $this->render('detail', ['warehouse' => $warehouse, 'supplier' => $supplier, 'order' => $order]);
    }

    public function actionGetDetail()
    {

        $data = Yii::$app->request->post();
        if (!isset($data['orderNo'])) {
            $this->retJson('参数错误', 500);
        }
        //订单信息
        $order = null;
        if (isset($data['orderNo']) && !empty($data['orderNo'])) {
            $sql = "SELECT po.*,wh.warehouseName,sp.supplierName FROM j_purchase_order po LEFT JOIN j_warehouse wh ON wh.id = po.warehouseId LEFT JOIN j_supplier sp ON sp.id = po.supplierId WHERE po.orderNo='" . $data['orderNo'] . "'";
            $order = Yii::$app->db->createCommand($sql)->queryOne();

            $sql = "SELECT pod.*,m.safeDay FROM j_purchase_order_details pod JOIN j_materiel m ON pod.materielId = m.id WHERE pod.orderNo = '" . $data['orderNo'] . "'";
            $orderDtl = Yii::$app->db->createCommand($sql)->queryAll();
            $order['dtl'] = $orderDtl;

        }
        return \yii\helpers\Json::encode($order);
    }




    public function actionSaveOrder(){
        $data = Yii::$app->request->post();


        if (!isset($data['materiels']) || !is_array($data['materiels']) || !isset($data['warehouseId']) || !isset($data['supplierId'])) {
            $this->retJson('参数错误', 500);
        }

        if (isset($data['orderNo']) && !empty($data['orderNo'])) {
            $orderNo = $data['orderNo'];

            $sql = "SELECT status FROM j_purchase_order  WHERE orderNo='" . $data['orderNo'] . "'";
            $order = Yii::$app->db->createCommand($sql)->queryOne();
            if($order['status'] != 0){
                $this->retJson('该采购订单状态不可编缉', 500);
            }

        } else {
            $orderNo = "PO". date('YmdHis').random_int(10,99);
        }

        $order = [
            'orderNo'=>$orderNo,
            'warehouseId'=>$data['warehouseId'],
            'supplierId'=>$data['supplierId'],
            'purchaseDate'=>$data['purchaseDate'],
            'purchaserName'=>$data['purchaserName'],
            'pre_deliveryDate'=>$data['pre_deliveryDate'],
            'contactName'=>$data['contactName'],
            'contactMobile'=>$data['contactMobile'],
            'receiverName'=>$data['receiverName'],
            'receiverInformation'=>$data['receiverInformation'],
            'deliveryAddress'=>$data['deliveryAddress'],
            'description'=>$data['description'],
            'remark'=>$data['remark'],
        ];

        $model = new Materiel();
        $materiels = [];
        foreach ($data['materiels'] as $m){

            $mdetail =  $ckMa = $model::find()->where(['id' => $m['materielId']])->asArray()->one();

            $materiels[] = [
                'orderNo'=>$orderNo,
                'materielId'=> $mdetail['id'],
                'materielCode'=> $mdetail['materielCode'],
                'materielName'=> $mdetail['materielName'],
                'specDesc'=> $mdetail['specDesc'],
                'orderUnit'=> $mdetail['orderUnit'],
                'purchaseUnit'=> $mdetail['purchaseUnit'],
                'packDesc'=> $mdetail['packDesc'],
                'taxRate'=> $m['taxRate'],
                'referPrice'=> $m['referPrice'],
                'price'=> $m['price'],
                'qty'=> $m['qty'],
                'totalPrice'=> $m['totalPrice'],
                'remark'=> $m['remark'],

            ];
        }

        $model = new PurchaseOrder();
        $currentDate = date('Y-m-d H:i:s');
        try {
            $transaction = Yii::$app->db->beginTransaction();

            if (isset($data['orderNo']) && !empty($data['orderNo'])) {
                $order['editor'] = $model->getCreator();
                $order['edit_time'] = $currentDate;
                $sql = "DELETE FROM j_purchase_order_details WHERE orderNo='" . $order['orderNo'] . "'";
                Yii::$app->db->createCommand($sql)->execute();
                $model::updateAll($order, "orderNo=:orderNo", array(':orderNo' => $orderNo));

            } else {
                $order['creator'] = $model->getCreator();
                $order['create_time'] = $currentDate;
                $order['status'] = 0;
                Yii::$app->db->createCommand()->insert('j_purchase_order', $order)->execute();
            }

            foreach ($materiels as $dtl) {
                Yii::$app->db->createCommand()->insert('j_purchase_order_details', $dtl)->execute();
            }

            $transaction->commit();
            $this->retJson('保存成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log($e->getMessage());
            $this->retJson('操作失败', 500);
        }

    }


}